<!DOCTYPE html>
<html>
<head>
    <script>
        var app = parent.app;
        var context = parent.context;
        var pageParm = parent.pageParm;
        parent.pageParm = {};
    </script>
    <style>
        html, body {
            background-color: transparent !important;
            overflow-x: hidden;
            overflow-y: auto;
        }
    </style>
    <title data-culture="articleManagment">信息发布</title>
    <link href="/assets/css/jquery-ui-1.8.7.custom.css" type="text/css" rel="stylesheet">
    <link href="/assets/css/mail.css" type="text/css" rel="stylesheet">

    <link href="/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/css/font-sans.min.css" rel="stylesheet" type="text/css"/>
    <script>
        var csss = ['/assets/css/page.css',
            '/assets/css/bootstrap-datetimepicker.css',
            '/assets/css/jquery.bootgrid.css',
            '/assets/css/route.css'
        ];
        for (m = 0; m < csss.length; m++) {
            document.write('<link href="' + csss[m] + '?license=' + new Date().getTime() + '" rel="stylesheet" />');
        }
    </script>
    <link href="/assets/css/typicons.min.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/css/animate.min.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css"/>
    <link href="/assets/js/ztree/css/metroStyle/metroStyle.css" rel="stylesheet" type="text/css"/>
    <script src="/assets/js/jquery.min.js" type="text/javascript"></script>
    <script src="/assets/js/jquery.cookie.js"></script>
    <script src="/assets/js/jquery-1.10.2.plugin.js"></script>
    <script src="/assets/js/culture.js"></script>

    <script src="/assets/js/moment.js" type="text/javascript"></script>
    <script src="/assets/js/ztree/jquery.ztree.all-3.5.js"></script>
    <script src="/assets/js/selectpicker/jquery.selectpicker.js"></script>
    <script src="/assets/js/validation/jquery.bootvalidate.js"></script>
    <script src="/assets/js/slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
    <script type="text/javascript" charset="utf-8" src="/assets/js/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="/assets/js/ueditor/ueditor.all.min.js"></script>
    <!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
    <script type="text/javascript" charset="utf-8" src="/assets/js/ueditor/lang/zh-cn/zh-cn.js"></script>
    <script src="/assets/js/skins.min.js"></script>
    <script src="/assets/js/utility.js"></script>
    <script src="/assets/js/jquery-ui-1.9.2.custom.js"></script>
    <script src="/assets/js/bootstrap.min.js" type="text/javascript"></script>
    <script src="/assets/js/bootbox/bootbox.js" type="text/javascript"></script>
    <script src="/assets/js/emailTool.js" charset="UTF-8"></script>
</head>
<body>
<div style="height: 100%;width: 100%; overflow-x: hidden;overflow-y: auto;">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12 col-sm-12 col-xs-12">
                <div class="widget  no-padding">
                    <div class="widget-header bg-themeprimary">
                        <i class="widget-icon typcn typcn-th-list"></i>
                        <span class="widget-caption" data-culture="articleList">写信</span>
                        <div class="toolbar">
                            <a data-event="5" id="btn_back">
                                <i class="glyphicon glyphicon-send"></i>还原
                            </a>
                            <a data-event="6" id="btn_delete1">
                                <i class="glyphicon glyphicon-send"></i>删除
                            </a>
                            <a data-event="7" id="btn_delete2">
                                <i class="glyphicon glyphicon-send"></i>彻底删除
                            </a>
                            <a data-event="0" id="btn_send" data-loading-text="发送中...">
                                <i class="glyphicon glyphicon-send"></i>立即发送
                            </a>
                            <a data-event="1" id="btn_save" data-loading-text="保存中...">
                                <i class="glyphicon glyphicon-send"></i>保存草稿
                            </a>
                            <a data-event="2" id="btn_replay">
                                <i class="glyphicon glyphicon-send"></i>回复
                            </a>
                            <a data-event="3" id="btn_replayall">
                                <i class="glyphicon glyphicon-send"></i>全部回复
                            </a>
                            <a data-event="4" id="btn_transfer">
                                <i class="glyphicon glyphicon-send"></i>转发
                            </a>

                        </div>
                    </div>
                    <div class="widget-body">
                        <form class="form-horizontal" role="form" id="form_article">
                            <div class="form-group">
                                <label class="col-sm-1 control-label no-padding-right" for="sender">发件人</label>
                                <div class="col-sm-11">
                                    <label id="sender" class="control-label no-padding-right">发件人</label>
                                </div>
                            </div>
                            <div class="form-group">
                                <a class="col-sm-1 control-label no-padding-right" id="sel_receiver" href="#">收件人</a>
                                <div class="col-sm-11">
                                    <div class="divtxt" id="divtxtReceiver"></div>
                                    <input type="hidden" id="sel_user_type"/>

                                </div>
                            </div>
                            <div class="form-group">
                                <a class="col-sm-1 control-label no-padding-right" id="sel_copyer" href="#">抄送人</a>
                                <div class="col-sm-11">
                                    <div class="divtxt" id="divtxtCopyer"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-1 control-label no-padding-right" for="title">标题</label>
                                <div class="col-sm-11">
                                    <input type="text" class="form-control" id="title" name="title"
                                           placeholder="标题">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-1 control-label no-padding-right" for="attachment">附件</label>
                                <div class="col-sm-11">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-1 control-label no-padding-right" for="editor">内容</label>
                                <div class="col-sm-11">
                                    <script id="editor" type="text/plain" style="height:260PX; width:100%;">
                                    </script>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel"
     aria-hidden="true" id="userTreeModal">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="widget no-padding">
                <div class="widget-header bg-themeprimary">
                    <i class="widget-icon glyphicon glyphicon-book"></i>
                    <span class="widget-caption">选择人员</span>
                    <div class="widget-buttons">
                        <a data-dismiss="modal">
                            <i class="fa fa-times"></i>
                        </a>
                    </div>
                </div>
                <div class="widget-body">
                    <ul id="userTree" class="ztree" style="width:auto; overflow:auto;"></ul>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btnChooseUser" class="btn btn-success">
                        确定
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var bootbox = new bootbox();
    var articleObj = {
        user1s: {},
        user2s: {},
        f: [],
        from: $.getUrlParam("from"),
        insert: (pageParm != undefined && pageParm.form != undefined) ? false : true,
        id: $.getUrlParam("id"),
        isZG: $.getUrlParam("isZG"),
        readStatus: $.getUrlParam("readStatus"),
        messageActionId: $.getUrlParam("messageActionId"),
        ue: UE.getEditor('editor'),
        currentArticle: (pageParm != undefined && pageParm.form != undefined) ? pageParm.form : {},
        userId: $.cookie(app.name + '_userId'),
        userName: $.cookie(app.name + '_name'),
        sender: {},
        receivers: [],
        copyers: [],
        userTreeObj: {},
        validateParam: {
            submitBtn: $('.toolbar').children(),
            submitHandler: function (obj, form, btn) {
                switch (btn.data('event')) {
                    case 0:
                        send(obj, btn);
                        break;
                    case 1:
                        save(obj);
                        break;
                    case  2:
                        replay(obj);
                        break;
                    case  3:
                        replayAll(obj);
                        break;
                    case  4:
                        transfer(obj);
                        break;
                    case 5:
                        deleteAction(articleObj.messageActionId, 0, articleObj.from, "还原");
                        break;
                    case 6:
                        if (articleObj.from == 3) {
                            deleteMessage(articleObj.id);
                        }
                        else {
                            deleteAction(articleObj.messageActionId, 1, articleObj.from, "删除");
                        }
                        break;
                    case 7:
                        deleteAction(articleObj.messageActionId, 2, articleObj.from, "删除");
                        break;
                    default:
                        break;
                }
            },
            fields: {
                title: {
                    validators: {
                        notEmpty: {}
                    }
                }
            }
        }
    };
    function validateUser(ctl_Id) {
        if ($("#" + ctl_Id + " .error").html() != null)
            return false;
        return true;
    }
    function send(obj, btn) {
        if ($("#divtxtReceiver .one").html() == null) {
            parent.bootbox.alert('收件人不能为空！');
            return;
        }
        if (!validateUser("divtxtReceiver")) {
            parent.bootbox.alert('收件人格式非法！');
            return;
        }
        if (!validateUser("divtxtCopyer")) {
            parent.bootbox.alert('抄送人格式非法！');
            return;
        }
        btn.button('loading');
        obj.insert = articleObj.insert;
        obj.id = articleObj.id;
        obj.data = escape(articleObj.ue.getContent());
        obj.sort = 1;
        obj.status = 1;
        obj.messageActions = [];
        obj.receiveUserNames = "";
        obj.copyUserNames = "";
        obj.messageActions.push(articleObj.sender);
        var receives = readUser("divtxtReceiver");
        for (var i = 0; i < receives.length; i++) {
            obj.messageActions.push(
                    {
                        userId: receives[i].id,
                        userName: receives[i].nickName,
                        readStatus: 0,
                        type: 1,
                        storeStatus: 0
                    }
            );
            if (obj.receiveUserNames !== "") {
                obj.receiveUserNames += ";"
            }
            obj.receiveUserNames += receives[i].nickName;
        }
        var copyers = readUser("divtxtCopyer");
        for (var i = 0; i < copyers.length; i++) {
            obj.messageActions.push(
                    {
                        userId: copyers[i].id,
                        userName: copyers[i].nickName,
                        readStatus: 0,
                        type: 2,
                        storeStatus: 0
                    }
            );
            if (obj.copyUserNames !== "") {
                obj.copyUserNames += ";"
            }
            obj.copyUserNames += copyers[i].nickName;
        }
        $.request("/message/save", obj, function (result) {
            parent.bootbox.alert('发送成功！');
        }, function () {
            parent.bootbox.alert('发送失败！');
        }).always(function () {
            $('#btn_send').button('reset');
            resetForm();
        });
    }
    function save(obj) {
        $('#btn_save').button('loading');
        obj.insert = articleObj.insert;
        obj.id = articleObj.id;
        obj.data = escape(articleObj.ue.getContent());
        obj.sort = 1;
        obj.status = 0;
        obj.messageActions = [];
        obj.receiveUserNames = "";
        obj.copyUserNames = "";
        obj.messageActions.push(articleObj.sender);
        var receives = readUser("divtxtReceiver");
        for (var i = 0; i < receives.length; i++) {
            obj.messageActions.push(
                    {
                        userId: receives[i].id,
                        userName: receives[i].nickName,
                        readStatus: 0,
                        type: 1,
                        storeStatus: 0
                    }
            );
            if (obj.receiveUserNames !== "") {
                obj.receiveUserNames += ";"
            }
            obj.receiveUserNames += receives[i].nickName;
        }
        var copyers = readUser("divtxtCopyer");
        for (var i = 0; i < copyers.length; i++) {
            obj.messageActions.push(
                    {
                        userId: copyers[i].id,
                        userName: copyers[i].nickName,
                        readStatus: 0,
                        type: 2,
                        storeStatus: 0
                    }
            );
            if (obj.copyUserNames !== "") {
                obj.copyUserNames += ";"
            }
            obj.copyUserNames += copyers[i].nickName;
        }
        $.request("/message/save", obj, function (result) {
            parent.bootbox.alert('保存成功！');
        }, function () {
            parent.bootbox.alert('保存失败！');
        }).always(function () {
            $('#btn_save').button('reset');
            resetForm();
        });
    }
    function replay() {
        var _receivers = [];
        articleObj.id = null;
        articleObj.insert = true;
        writeUser("divtxtReceiver", [articleObj.sender]);
        $("#sender").html(articleObj.userName);
        articleObj.sender = {userId: articleObj.userId, userName: articleObj.userName, type: 0, storeStatus: 0};
        $("#divtxtCopyer").html("");
        var _title = $("#title").val();
        $("#title").val("回复:" + _title);
        setBtnStatus(1);
    }
    function replayAll() {
        articleObj.id = null;
        articleObj.insert = true;
        var _receivers = [];
        _receivers.push(articleObj.user2s[articleObj.sender.userId]);
        $("#sender").html(articleObj.userName);
        articleObj.sender = {userId: articleObj.userId, userName: articleObj.userName, type: 0, storeStatus: 0};
        receiverNames = articleObj.userName;
        $.each(readUser("divtxtReceiver"), function (index, receiver) {
            _receivers.push(receiver);
        });
        $.each(readUser("divtxtCopyer"), function (index, copyer) {
            _receivers.push(copyer);
        });
        writeUser("divtxtReceiver", _receivers);
        $("#divtxtCopyer").html("");
        var _title = $("#title").val();
        $("#title").val("回复:" + _title);
        setBtnStatus(1);
    }
    function transfer() {
        articleObj.id = null;
        articleObj.insert = true;
        $("#sender").html(articleObj.userName);
        articleObj.sender = {userId: articleObj.userId, userName: articleObj.userName, type: 0, storeStatus: 0};
        $("#divtxtReceiver").html("");
        $("#divtxtCopyer").html("");
        var _title = $("#title").val();
        $("#title").val("转发:" + _title);
        setBtnStatus(1);
    }
    $('#btnChooseUser').click(function () {
        var nodes = articleObj.userTreeObj.getCheckedNodes(true);
        var value = "";
        var sel_user_type = $("#sel_user_type").val();
        var users = [];
        var ctl = "";
        if (sel_user_type == 1) {
            ctl = "divtxtReceiver";
        }
        else {
            ctl = "divtxtCopyer";
        }
        $.each(nodes, function (i, item) {
            if (!item.isParent) {
                users.push({userId:item.id});
            }
        });
        writeUser(ctl, users);
        $('#userTreeModal').modal('hide');
    });
    function initUser() {
        articleObj.userTreeObj = $('#userTree').tree({
            data: {
                key: {name: 'orgName', enname: 'orgEnName'},
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: 0,
                    url: '/admin/sys/org/user/query/all'
                }
            },
            check: {
                enable: true
            },
            expandLevel: 3
        });
        $.request("/admin/sys/user/query/all", {}, function (data) {
            $.each(data, function (index, _data) {
                articleObj.user1s[_data.loginName] = _data;
                articleObj.user2s[_data.id] = _data;
                articleObj.f.push(_data.nickName + "<" + _data.loginName + ">");
            })
        });
    }
    function writeUser(ctl_Id, users) {
        $("#" + ctl_Id).html("");
        $.each(users, function (index, user) {
            var id = user.userId;
            var _user = articleObj.user2s[id];
            if (_user === undefined)  return;
            $("#" + ctl_Id).append($.format("<div class='one'><b>{0}</b><<span title='{1}' class='addr'>{1}</span>>;</div>"
                    , _user.nickName, _user.loginName));
        })
    }
    function readUser(ctl_Id) {
        var users = [];
        $("#" + ctl_Id + " .one .addr").each(function (index, addr) {
            var loginName = $.trim($(addr).html());
            var user = articleObj.user1s[loginName];
            if (user === undefined) return;
            users.push(user);
        });
        return users;
    }
    function resetForm() {
        articleObj.id = null;
        articleObj.insert = true;
        articleObj.validateParam.resetBtn.trigger("reset");
        articleObj.sender = {userId: articleObj.userId, userName: articleObj.userName, type: 0, storeStatus: 0};
        $("#sender").html(articleObj.userName);
        articleObj.ue.setContent("");
        $("#sel_user_type").val(null);
        $("#divtxtReceiver").html("");
        $("#divtxtCopyer").html("");
    }
    function setTitle() {
        if (articleObj.from == 1) {
            $(".widget-caption").html("收件箱");
        }
        else if (articleObj.from == 2) {
            $(".widget-caption").html("发件箱");
        }
        else if (articleObj.from == 3) {
            $(".widget-caption").html("草稿箱");
        } else if (articleObj.from == 4) {
            $(".widget-caption").html("垃圾箱");
        }
        else {
            $(".widget-caption").html("写信");
        }
    }
    function init() {
        setTitle();
        initUser();
        $("#sel_receiver").click(function () {
            $("#sel_user_type").val(1);
            articleObj.userTreeObj.checkAllNodes(false);
            $('#userTreeModal').modal('show');
        });
        $("#sel_copyer").click(function () {
            $("#sel_user_type").val(2);
            articleObj.userTreeObj.checkAllNodes(false);
            $('#userTreeModal').modal('show');
        });
        if (articleObj.id === undefined || articleObj.id === null) {
            articleObj.insert = true;
            setBtnStatus(1);
            $("#sender").html(articleObj.userName);
            articleObj.sender = {userId: articleObj.userId, userName: articleObj.userName, type: 0, storeStatus: 0};
        }
        else {
            if (articleObj.isZG !== undefined && articleObj.isZG !== null) {
                setBtnStatus(1);
                articleObj.insert = false;
            }
            else {
                setBtnStatus(2, articleObj.from);
            }
            if (articleObj.readStatus === '0') {
                $.request('/message/updateAction/id', {
                    id: articleObj.messageActionId,
                    readStatus: 1
                }, function (result) {
                });
            }
            var _receivers = [];
            var _copyers = [];
            $.request('/message/query/id', {id: articleObj.id}, function (result) {
                $.each(result.messageActions, function (index, item) {
                    switch (item.type) {
                        case 0:
                            articleObj.sender = {userId: item.userId, userName: item.userName, type: 0, storeStatus: 0};
                            $("#sender").html(item.userName);

                            break;
                        case 1:
                            _receivers.push({userId: item.userId});
                            break;
                        case 2:
                            _copyers.push({userId: item.userId});
                            break;
                        default:
                            break;
                    }
                });
                writeUser("divtxtReceiver", _receivers);
                writeUser("divtxtCopyer", _copyers);
                $('#title').val(result.title);
                var content = unescape(result.data);
                articleObj.ue.ready(function () {
                    articleObj.ue.setContent(content, true)
                });
            })
        }
        $('#form_article').validate(articleObj.validateParam);
    }
    function setBtnStatus(status, from) {
        switch (status) {
            case 1:
                $(".widget-caption").html("写信");
                $("#btn_replay").css("display", "none");
                $("#btn_replayall").css("display", "none");
                $("#btn_transfer").css("display", "none");
                $("#btn_send").css("display", "inline");
                $("#btn_save").css("display", "inline");
                $("#btn_delete1").css("display", "none");
                $("#btn_delete2").css("display", "none");
                $("#btn_back").css("display", "none");
                break;
            case 2:
                setTitle();
                if (from == 4) {
                    $("#btn_back").css("display", "inline");
                    $("#btn_delete1").css("display", "none");
                }
                else {
                    $("#btn_back").css("display", "none");
                    $("#btn_delete1").css("display", "inline");
                    $("#btn_delete2").css("display", "inline");
                }
                $("#btn_replay").css("display", "inline");
                $("#btn_replayall").css("display", "inline");
                $("#btn_transfer").css("display", "inline");
                $("#btn_send").css("display", "none");
                $("#btn_save").css("display", "none");
                break;
            default:
                break;
        }
    }
    $(function () {
        init();
    });
    function deleteAction(id, storeStatus, from, msg) {
        if (!confirm($.format("确认{0}吗？", msg)))return;
        $.request('/message/deleteAction/ids', {ids: [id], storeStatus: storeStatus}, function () {
            var url = "";
            if (from == 1) url = "/views/message/receiving.html";
            else if (from == 2) url = "/views/message/sending.html";
            else if (from == 4) url = "/views/message/garbaging.html";
            parent.loadpage(url);
        }, function () {
            bootbox.alert(msg + "失败!");
        })
    }
    function deleteMessage(id) {
        if (!confirm("确认删除吗？"))return;
        $.request('/message/deleteMessage/ids', {ids: [id]}, function () {
            parent.loadpage("/views/message/drafting.html");
        }, function () {
            bootbox.alert("删除失败!");
        })
    }

</script>
</body>
</html>